package com.laker.autotest.core;

import cn.hutool.extra.spring.SpringUtil;
import com.laker.autotest.config.EasyConfig;
import com.laker.autotest.utils.TestNGUtil;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.options.ScreenshotScale;
import lombok.extern.slf4j.Slf4j;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

import java.nio.file.Paths;

@Slf4j
public class ScreenshotListener extends TestListenerAdapter {

    @Override
    public void onTestFailure(ITestResult tr) {
        EasyConfig config = SpringUtil.getBean(EasyConfig.class);
        if (!config.getTraceOptions().screenshotEnable) {
            return;
        }
        try {
            BasePageTest basePage = (BasePageTest) tr.getInstance();
            log.warn("[Screenshot], {} CaseName: {}.{} test failure!", basePage.hashCode(),
                    basePage.getClass().getSimpleName(), tr.getMethod().getMethodName());
            Page page = basePage.getPage();
            page.screenshot(new Page.ScreenshotOptions()
                    .setPath(Paths.get(TestNGUtil.getScreenShotPath(tr)))
                    .setScale(ScreenshotScale.CSS)
                    .setTimeout(10000)
                    .setFullPage(false));
        } catch (Exception e) {
            log.error("screenshot error, msg:{}", e.getMessage());
        }
    }

}
